<script setup lang="ts">
import type { OptionItem } from "../../apis/type"
import type { PositionAddOrUpdateRequest } from "@/pages/internship/position/position-teacher/apis/type"
import { Calendar, Document, InfoFilled } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, nextTick, reactive, ref, watch } from "vue"
import { usePositionTeacherStore } from "@/pinia/stores/position-teacher"

const props = defineProps<{
  modelValue: boolean
  positionId?: number
}>()

const emit = defineEmits<{
  "update:modelValue": [value: boolean]
  "close": []
  "success": []
}>()

// 使用store
const positionTeacherStore = usePositionTeacherStore()

// 直接从store计算获取选项数据 - 仿照CompanyDetailModal.vue模式
const workTypeOptions = computed(() => positionTeacherStore.workTypeOptions)
const workCityOptions = computed(() => positionTeacherStore.workCityOptions)
const periodOptions = computed(() => positionTeacherStore.periodOptions)
const salaryOptions = computed(() => positionTeacherStore.salaryOptions)
const positionTypeOptions = computed(() => positionTeacherStore.positionTypeOptions)
const companyOptions = computed(() => positionTeacherStore.companyOptions)

// 表单数据
const formData = reactive<PositionAddOrUpdateRequest>({
  companyId: undefined,
  companyName: "",
  positionName: "",
  positionType: undefined,
  workType: undefined,
  workCity: undefined,
  workPlace: "",
  salary: undefined,
  period: undefined,
  startDate: "",
  recruitNum: 1,
  positionDesc: "",
  positionRequire: "",
  publishUserId: 0,
  deadline: "",
  status: 56,
  isRecommend: 0
})

// 表单验证规则
const rules = reactive({
  positionName: [
    { required: true, message: "请输入职位名称", trigger: "blur" },
    { min: 2, max: 50, message: "职位名称长度应为2-50个字符", trigger: "blur" }
  ],
  companyId: [
    { required: true, message: "请选择公司", trigger: "change" }
  ],
  positionType: [
    { required: true, message: "请选择职位类型", trigger: "change" }
  ],
  workType: [
    { required: true, message: "请选择工作类型", trigger: "change" }
  ],
  workCity: [
    { required: true, message: "请选择工作城市", trigger: "change" }
  ],
  salary: [
    { required: true, message: "请选择薪资范围", trigger: "change" }
  ],
  period: [
    { required: true, message: "请选择实习周期", trigger: "change" }
  ],
  startDate: [
    { required: true, message: "请选择任职开始时间", trigger: "change" }
  ],
  recruitNum: [
    { required: true, message: "请输入招聘人数", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value < 1 || value > 100) {
          callback(new Error("招聘人数应为1-100人"))
        } else {
          callback()
        }
      },
      trigger: "blur"
    }
  ],
  positionRequire: [
    { required: true, message: "请输入任职要求", trigger: "blur" },
    { min: 10, max: 500, message: "任职要求长度应为10-500个字符", trigger: "blur" }
  ],
  positionDesc: [
    { required: true, message: "请输入岗位职责", trigger: "blur" },
    { min: 10, max: 1000, message: "岗位职责长度应为10-1000个字符", trigger: "blur" }
  ],
  deadline: [
    { required: true, message: "请选择报名截止日期", trigger: "change" }
  ]
})

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: value => emit("update:modelValue", value)
})
const formRef = ref()
const loading = ref(false)
const submitLoading = ref(false)

// 监听modelValue变化，更新本地visible变量 - 仿照CompanyDetailModal.vue模式
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue
})

// 监听逻辑 - 仿照CompanyEditModal.vue模式
watch([() => props.positionId, () => props.modelValue], async ([newPositionId, newVisible]) => {
  if (newVisible) {
    // 加载选项数据
    await positionTeacherStore.fetchOptions()

    if (newPositionId && newPositionId > 0) {
      loadPositionData(newPositionId)
    } else {
      console.log("新增模式")
      resetForm()
    }
  }
}, { immediate: true })

async function loadPositionData(positionId: number) {
  console.log("开始加载职位数据，ID:", positionId)
  loading.value = true
  try {
    // 先重置表单，避免旧数据残留
    resetForm()

    // 调用store中的方法获取职位详情
    const detailData = await positionTeacherStore.fetchPositionDetail(positionId)

    if (detailData) {
      // 确保表单引用已经初始化
      await nextTick()

      // 填充表单数据 - 将字符串值转换为对应的数字ID
      Object.assign(formData, {
        positionId: detailData.positionId,
        companyId: detailData.companyId,
        companyName: detailData.companyName,
        positionName: detailData.positionName,
        positionType: getOptionValue(detailData.positionType, positionTypeOptions.value),
        workType: getOptionValue(detailData.workType, workTypeOptions.value),
        workCity: getOptionValue(detailData.workCity, workCityOptions.value),
        workPlace: detailData.workPlace || "",
        salary: getOptionValue(detailData.salary, salaryOptions.value),
        period: getOptionValue(detailData.period, periodOptions.value),
        startDate: detailData.startDate,
        recruitNum: detailData.recruitNum,
        positionDesc: detailData.positionDesc || "",
        positionRequire: detailData.positionRequire || "",
        deadline: detailData.deadline,
        status: getStatusValue(detailData.status),
        isRecommend: detailData.isRecommend ? 1 : 0
      })

      console.log("表单数据填充完成:", formData)
    } else {
      console.warn("未找到职位详情数据")
      ElMessage.warning("未找到职位详情数据")
    }
  } catch (error) {
    console.error("加载职位数据失败:", error)
    ElMessage.error("加载职位数据失败")
  } finally {
    loading.value = false
  }
}

// 根据选项标签获取对应的值
function getOptionValue(label: string, options: OptionItem[]): number {
  const option = options.find(opt => opt.label === label)
  return option ? option.value : 0
}

// 根据状态字符串获取对应的数字值
function getStatusValue(status: string): number {
  switch (status) {
    case "招聘中": return 56
    case "已截止": return 55
    case "暂停招聘": return 57
    default: return 56
  }
}

// 处理公司选择变化
function handleCompanyChange(companyId: number) {
  if (companyId) {
    const selectedCompany = companyOptions.value.find(option => option.value === companyId)
    if (selectedCompany) {
      formData.companyName = selectedCompany.label
    }
  } else {
    formData.companyName = ""
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.positionId = 0
  Object.assign(formData, {
    companyId: undefined,
    companyName: "",
    positionName: "",
    positionType: undefined,
    workType: undefined,
    workCity: undefined,
    workPlace: "",
    salary: undefined,
    period: undefined,
    startDate: "",
    recruitNum: 1,
    positionDesc: "",
    positionRequire: "",
    publishUserId: 0, // TODO: 需要从用户信息中获取
    deadline: "",
    status: 56, // 默认招聘中
    isRecommend: 0
  })
}

// 关闭弹窗
function handleClose() {
  emit("update:modelValue", false)
  emit("close")
  // 延迟重置，避免动画期间的数据残留
  setTimeout(() => {
    resetForm()
  }, 300)
}

// 保存数据
async function handleSave() {
  try {
    // 表单验证
    await formRef.value.validate()

    submitLoading.value = true

    let success = false
    if (props.positionId && props.positionId > 0) {
      // 更新职位
      success = await positionTeacherStore.updatePosition({ ...formData })
    } else {
      // 新增职位
      success = await positionTeacherStore.addPosition({ ...formData })
    }

    if (success) {
      emit("success")
      setTimeout(() => {
        handleClose()
      }, 100)
    }
  } catch (error) {
    console.error("保存职位信息失败:", error)
    ElMessage.error("保存职位信息失败")
  } finally {
    submitLoading.value = false
  }
}
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="props.positionId && props.positionId > 0 ? `${formData.positionName || '编辑职位'}` : '新增职位'"
    width="900px"
    :loading="loading || submitLoading"
    @close="handleClose"
    class="position-edit-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="position-edit-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><InfoFilled /></el-icon>
          基本信息
        </h3>

        <div class="form-row">
          <el-form-item label="职位名称" prop="positionName">
            <el-input
              v-model="formData.positionName"
              placeholder="请输入职位名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="公司" prop="companyId">
            <el-select
              v-model="formData.companyId"
              placeholder="请选择公司"
              filterable
              clearable
              @change="handleCompanyChange"
            >
              <el-option
                v-for="option in companyOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="职位类型" prop="positionType">
            <el-select
              v-model="formData.positionType"
              placeholder="请选择职位类型"
              filterable
              clearable
            >
              <el-option
                v-for="option in positionTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="工作类型" prop="workType">
            <el-select
              v-model="formData.workType"
              placeholder="请选择工作类型"
              filterable
              clearable
            >
              <el-option
                v-for="option in workTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="工作城市" prop="workCity">
            <el-select
              v-model="formData.workCity"
              placeholder="请选择工作城市"
              filterable
              clearable
            >
              <el-option
                v-for="option in workCityOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="薪资范围" prop="salary">
            <el-select
              v-model="formData.salary"
              placeholder="请选择薪资范围"
              filterable
              clearable
            >
              <el-option
                v-for="option in salaryOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="工作地点" prop="workPlace">
            <el-input
              v-model="formData.workPlace"
              placeholder="请输入详细工作地点"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </div>
      </div>

      <!-- 时间信息 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><Calendar /></el-icon>
          时间信息
        </h3>

        <div class="form-row">
          <el-form-item label="实习周期" prop="period">
            <el-select
              v-model="formData.period"
              placeholder="请选择实习周期"
              filterable
              clearable
            >
              <el-option
                v-for="option in periodOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="任职开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              placeholder="请选择任职开始时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="报名截止日期" prop="deadline">
            <el-date-picker
              v-model="formData.deadline"
              type="date"
              placeholder="请选择报名截止日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="招聘人数" prop="recruitNum">
            <el-input-number
              v-model="formData.recruitNum"
              :min="1"
              :max="100"
              placeholder="请输入招聘人数"
              style="width: 100%"
            />
          </el-form-item>
        </div>
      </div>

      <!-- 职位要求 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><Document /></el-icon>
          职位要求
        </h3>

        <div class="form-row">
          <el-form-item label="技能要求" prop="positionRequire">
            <el-input
              v-model="formData.positionRequire"
              placeholder="请输入技能要求"
              maxlength="500"
              show-word-limit
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="岗位职责" prop="positionDesc">
            <el-input
              v-model="formData.positionDesc"
              placeholder="请输入岗位职责"
              maxlength="1000"
              show-word-limit
              type="textarea"
              :rows="4"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="submitLoading">
        {{ props.positionId && props.positionId > 0 ? `更新` : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-dialog) {
  .el-dialog__header {
    background: #f8f9fa;
    padding: 20px 25px;
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 25px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
  }
}

.position-edit-dialog {
  .el-dialog__footer {
    padding: 15px 25px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.position-edit-form {
  .form-section {
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f2f5;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
    padding: 0 0 8px 0;
    border-bottom: 2px solid #1890ff;
  }

  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .el-form-item {
      flex: 1;
      margin-bottom: 0;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}

@media (max-width: 768px) {
  .position-edit-form {
    .form-row {
      flex-direction: column;
      gap: 16px;
    }
  }
}
</style>
